<?php

namespace User\Model;

use User\Model\Entity\ModuleSettings;
use Zend\Db\TableGateway\AbstractTableGateway;
use Zend\Db\Adapter\Adapter;
use Zend\Db\Sql\Select;

class ModuleSettingsModel extends AbstractTableGateway {
	protected $table = 'tb_user_module_settings';

	public function __construct(Adapter $adapter) {
		$this->adapter = $adapter;
	}

	public function saveModuleSettings(ModuleSettings $moduleSettings) {
		$data = array(
            'login_route'					=> $moduleSettings->getLoginRoute(),
            'redirect_route_login'			=> $moduleSettings->getRedirectRouteLogin(),
            'redirect_route_logout'			=> $moduleSettings->getRedirectRouteLogout(),
            'login_after_registration'		=> $moduleSettings->getLoginAfterRegistration(),
            'registration_enable'			=> $moduleSettings->getRegistrationEnable(),
            'registration_use_form_captcha'	=> $moduleSettings->getRegistrationUseFormCaptcha(),
		);
		
		$id = (int) $moduleSettings->getId();
		if(empty($id)) {
			$this->insert($data);
		} else {
			if($this->getModuleSettings($id)) {
				$this->update($data, array('user_module_settings_id' => $id));
			}
		}
	}
	
	public function getSettings() {
		$resultSet = $this->select(function (Select $select) {
			$select->where(array(
				'status' => true,
			));
		});

		$rowSet = $resultSet->current();

		if(!$rowSet) {
			throw new \Exception("Could not find row " . $id);
		}

		return new ModuleSettings((array) $rowSet);
	}
	
	public function getModuleSettings($id) {
		$resultSet = $this->select(function (Select $select) use ($id) {
			$select->where(array(
				'user_module_settings_id' => $id,
			));
		});

		$rowSet = $resultSet->current();

		if(!$rowSet) {
			throw new \Exception("Could not find row " . $id);
		}

		return new ModuleSettings((array) $rowSet);
	}
}